package com.wbao.dianniu.ui;


import java.util.ArrayList;

import android.app.Dialog;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.Toast;

import com.alibaba.mobileim.conversation.YWConversation;
import com.alibaba.mobileim.conversation.YWMessageChannel;
import com.baidu.location.BDLocation;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnMapLongClickListener;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MarkerOptions.MarkerAnimateType;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationConfiguration.LocationMode;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.CityInfo;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiCitySearchOption;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.umeng.analytics.MobclickAgent;
import com.wbao.dianniu.baidumap.PoiOverlay;
import com.wbao.dianniu.logical.Const;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.update.MapSearchHelper;
import com.wbao.dianniu.utils.Notification;
import com.wbao.dianniu.utils.PermissionUtils;
import com.wbao.dianniu.utils.Utils;
import com.wbao.dianniu.R;

public class MapActivity extends MapBaseActivity implements OnGetGeoCoderResultListener, OnGetPoiSearchResultListener,MapSearchHelper.IMapSearchListener {

    private EditText searchET;
    private EditText resultET;
    private Button confirmBtn;
    private LinearLayout resultLayout;
    private ImageButton requestLocButton;

    MapView mMapView = null;
    private BaiduMap mBaiduMap = null;
    //    private LocationClient mLocationClient = null;
//    private BDLocationListener myListener = new MyLocationListener();
    //	private LocationMode mCurrentMode;
    BitmapDescriptor mCurrentMarker;
    boolean isFirstLoc = true; // 是否首次定位
    private MyLocationData locData;
    private LatLng latlng;
    /**
     * 当前地点击点
     */
    private Marker mMarker;
    GeoCoder mSearch = null; // 搜索模块，也可去掉地图模块独立使用

    private PoiSearch mPoiSearch = null;
    private String city = "";

    // 上一个颜色
//	private LatLng preLatLng;
    PoiOverlay mOverlay;

    private static YWConversation conversation;
    private MapSearchHelper mapSearchHelper;

    public static void bindConversation(YWConversation conver) {
        conversation = conver;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentLayout(R.layout.activity_map_address, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        setTitleName("选择活动地点");
        initview();
        initMap();
        showPosition();

        mapSearchHelper = MapSearchHelper.getInstance();
        mapSearchHelper.addListener(this);
        // 初始化搜索模块，注册搜索事件监听
        mPoiSearch = PoiSearch.newInstance();
        mPoiSearch.setOnGetPoiSearchResultListener(this);

    }

    private void showPosition() {
        Intent intent = getIntent();
        double lat = intent.getDoubleExtra(Const.INTENT_MAP_LAT, 0);
        double lon = intent.getDoubleExtra(Const.INTENT_MAP_LONG, 0);
        latlng = new LatLng(lat, lon);
        if (0 != lat && 0 != lon) {
            mCurrentMarker = BitmapDescriptorFactory.fromResource(R.drawable.icon_gcoding);
            MarkerOptions ooA = new MarkerOptions().position(latlng).icon(mCurrentMarker)
                    .period(1)
                    .zIndex(2).draggable(false);
            // 掉下动画
            ooA.animateType(MarkerAnimateType.jump);
            mMarker = (Marker) (mBaiduMap.addOverlay(ooA));
            mMarker.setPosition(latlng);
            //显示当前位置
            MapStatus.Builder builder = new MapStatus.Builder();
            builder.target(latlng).zoom(18.0f);
            mBaiduMap.setMyLocationConfigeration(new MyLocationConfiguration(LocationMode.NORMAL, true, null));
            mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
        }
    }


    private void initview() {
        searchET = (EditText) findViewById(R.id.map_search_edittext01);
        resultET = (EditText) findViewById(R.id.map_address_name);
//		searchBtn = (ImageView) findViewById(R.id.map_search_iv01);
        confirmBtn = (Button) findViewById(R.id.map_confirm);
        resultLayout = (LinearLayout) findViewById(R.id.map_address_desc);
        requestLocButton = (ImageButton) findViewById(R.id.my_location_imagebutton);
//		searchBtn.setOnClickListener(this);
        confirmBtn.setOnClickListener(this);
        resultLayout.setVisibility(View.GONE);
        searchET.setOnClickListener(this);
    }

    private void initMap() {
        // 获取地图控件引用
        mMapView = (MapView) findViewById(R.id.bmapView);
        mBaiduMap = mMapView.getMap();
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        initLocation();
        requestLocButton.setOnClickListener(this);
        /**    长按地图	*/
        mBaiduMap.setOnMapLongClickListener(new OnMapLongClickListener() {

            public void onMapLongClick(LatLng point) {
                // 反Geo搜索
                mSearch.reverseGeoCode(new ReverseGeoCodeOption().location(point));
            }
        });

        // 初始化搜索模块，注册事件监听
        mSearch = GeoCoder.newInstance();
        mSearch.setOnGetGeoCodeResultListener(this);
    }

    @Override
    public void receiveLocation(BDLocation location) {
        if (location == null || mMapView == null) {
            return;
        }
        if (!TextUtils.isEmpty(location.getCity())) {
            GlobalContext.curLocation = location.getCity();
        }
        locData = new MyLocationData.Builder()
                .accuracy(location.getRadius())
                .latitude(location.getLatitude())
                .longitude(location.getLongitude()).build();
        mBaiduMap.setMyLocationData(locData);

        if (isFirstLoc) {
            isFirstLoc = false;
            LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
            MapStatus.Builder builder = new MapStatus.Builder();
            builder.target(ll).zoom(18.0f);
            mBaiduMap.setMyLocationConfigeration(new MyLocationConfiguration(LocationMode.NORMAL, true, null));
            mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mapSearchHelper) {
            mapSearchHelper.removeListener(this);
        }
        mSearch.destroy();
        // 关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);
//        mMapView.onDestroy();
//        mMapView = null;
        mPoiSearch.destroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mMapView.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.my_location_imagebutton:
                if (null == locData) {
                    Notification.toast(MapActivity.this, "无法获取当前位置");
                    return;
                }
                LatLng ll = new LatLng(locData.latitude, locData.longitude);
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(ll).zoom(18.0f);
                mBaiduMap.setMyLocationConfigeration(new MyLocationConfiguration(LocationMode.NORMAL, true, null));
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
                break;
            case R.id.map_confirm:
                String address = resultET.getText().toString().trim();
                if (!TextUtils.isEmpty(address)) {
                    Intent intent = new Intent();
                    if (null == latlng) {
                        latlng = new LatLng(0, 0);
                    }

                    if (null != conversation) {
                        conversation.getMessageSender().sendMessage(
                                YWMessageChannel.createGeoMessage(latlng.latitude,
                                        latlng.longitude, address), 120, null);
                        this.finish();
                    }

                    //把返回数据存入Intent
                    intent.putExtra(CreateActivity.RET_LAT, latlng.latitude);
                    intent.putExtra(CreateActivity.RET_LONG, latlng.longitude);
                    intent.putExtra(CreateActivity.RET_CITY, city);
                    intent.putExtra(CreateActivity.RET_ADDRESS, address);
                    //设置返回数据
                    setResult(RESULT_OK, intent);
                    finish();
                }
                break;
            case R.id.back_button:
                //把返回数据存入Intent
               /* Intent intent = new Intent();
                intent.putExtra(CreateActivity.RET_LAT, 0);
                intent.putExtra(CreateActivity.RET_LONG, 0);
                intent.putExtra(CreateActivity.RET_CITY, "");
                intent.putExtra(CreateActivity.RET_ADDRESS, "");
                //设置返回数据
                setResult(RESULT_OK, intent);*/
                finish();
                break;
            case R.id.map_search_edittext01:
               /* if (Build.VERSION.SDK_INT < 23) {

                } else {
                    boolean permission = getLocPermission();
                    if(!permission){
                        PermissionUtils.getInstance().showMsg(MapActivity.this, "权限被拒绝，此功能不能正常使用，\n请点击\"设置\"-\"权限管理\"-打开所有权限");
                        return;
                    }
                }*/
                if(TextUtils.isEmpty(GlobalContext.curLocation)){
                    GlobalContext.curLocation = "北京";
                }
                //点击输入框，跳转到搜索界面
                Intent searchIntent = new Intent();
                String searchContent = searchET.getText().toString().trim();
                searchIntent.putExtra(CreateActivity.RET_ADDRESS, searchContent);
                searchIntent.setClass(MapActivity.this, MapSearchActivity.class);
                startActivity(searchIntent);
                break;
            default:
                break;
        }
    }

//    /**
//     * 响应城市内搜索按钮点击事件(多选择时，默认显示第一个)
//     *
//     * @param citystr
//     * @param keystr
//     */
//    public static void searchButtonProcess(String citystr, String keystr) {
//
//    }


    /* (non-Javadoc)	地理编码查询结果回调函数 (通过地址得到经纬度)
     * @see com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener#onGetGeoCodeResult(com.baidu.mapapi.search.geocode.GeoCodeResult)
     */
    @Override
    public void onGetGeoCodeResult(GeoCodeResult result) {
    }

    /**
     * 反地理编码查询结果回调函数 (通过经纬度得到地址)
     */
    @Override
    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
        if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
            Notification.toast(MapActivity.this, "抱歉，未能找到结果");
            return;
        }
        latlng = result.getLocation();
        mBaiduMap.clear();
        mCurrentMarker = BitmapDescriptorFactory.fromResource(R.drawable.icon_gcoding);
        MarkerOptions ooA = new MarkerOptions().position(result.getLocation()).icon(mCurrentMarker)
                .period(1)
                .zIndex(2).draggable(true);
        // 掉下动画
        ooA.animateType(MarkerAnimateType.drop);
        mMarker = (Marker) (mBaiduMap.addOverlay(ooA));
        mMarker.setPosition(result.getLocation());
        showAddress(result.getAddress(), result.getAddressDetail().city);
    }

    private void showAddress(String address, String city) {
        this.city = city;
        resultLayout.setVisibility(View.VISIBLE);
        resultET.setText(address);
    }

    private void removeAddress() {
        resultET.setText("");
        resultLayout.setVisibility(View.GONE);
        latlng = null;
    }

    @Override
    public void onGetPoiDetailResult(PoiDetailResult result) {
    }

    @Override
    public void onGetPoiIndoorResult(PoiIndoorResult result) {

    }

    @Override
    public void onGetPoiResult(PoiResult result) {
        if (result == null || result.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) {
            Toast.makeText(MapActivity.this, "未找到结果", Toast.LENGTH_LONG).show();
            return;
        }
        if (result.error == SearchResult.ERRORNO.NO_ERROR) {
            mBaiduMap.clear();
            mOverlay = new MyPoiOverlay(mBaiduMap);
            mBaiduMap.setOnMarkerClickListener(mOverlay);
            mOverlay.setData(result);
            mOverlay.addToMap();
            mOverlay.zoomToSpan();
            mOverlay.showCurrentmarker(0);

            PoiInfo poiInfo = result.getAllPoi().get(0);
            latlng = poiInfo.location;
            showAddress(poiInfo.city + poiInfo.name + "(" + poiInfo.address + ")", poiInfo.city);
            return;
        }
        if (result.error == SearchResult.ERRORNO.AMBIGUOUS_KEYWORD) {
            // 当输入关键字在本市没有找到，但在其他城市找到时，返回包含该关键字信息的城市列表
            ArrayList<String> list = new ArrayList<String>();
            for (CityInfo cityInfo : result.getSuggestCityList()) {
                list.add(cityInfo.city);
            }
            showCitySelected(list);
        }
    }

    Dialog dialog;

    /**
     * 多城市选择
     *
     * @param citiys
     */
    private void showCitySelected(ArrayList<String> citiys) {
        dialog = new Dialog(this, R.style.custom_Dialog);
        try {
            Window win = dialog.getWindow();
            int padding = Utils.dip2px(this, 10);
            win.getDecorView().setPadding(padding, padding, padding, padding);
            win.setGravity(Gravity.CENTER);
            WindowManager.LayoutParams lp = win.getAttributes();
            lp.width = WindowManager.LayoutParams.MATCH_PARENT;
            lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
            win.setAttributes(lp);
        } catch (Exception e) {
            e.printStackTrace();
        }
        View view = LayoutInflater.from(this).inflate(R.layout.custom_city_selected_dialog, null);
        ListView listview = (ListView) view.findViewById(R.id.city_select_listview);
        final ArrayAdapter<String> adapter = new ArrayAdapter<>(this, R.layout.activity_citys_list_item, R.id.city_list_item, citiys);
        listview.setAdapter(adapter);
        listview.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                // 选择某个城市时，通过某个城市搜索
//                searchButtonProcess(adapter.getItem(position), searchET.getText().toString());
                searchPosition(adapter.getItem(position), searchET.getText().toString());
                dialog.dismiss();
            }
        });
        dialog.setContentView(view);
        dialog.setCancelable(true);
        dialog.show();
    }

    @Override
    public void searchPosition(String citystr, String keystr) {
        if (!TextUtils.isEmpty(keystr)) {
            searchET.setText(keystr);
            mPoiSearch.searchInCity((new PoiCitySearchOption()).city(citystr).keyword(keystr));
        }
    }


    private class MyPoiOverlay extends PoiOverlay {

        public MyPoiOverlay(BaiduMap baiduMap) {
            super(baiduMap);
        }


        @Override
        public boolean onPoiClick(Marker marker) {
            return true;
        }

        @Override
        public boolean onPoiClick(int index) {
//            super.onPoiClick(index);
            PoiInfo poi = getPoiResult().getAllPoi().get(index);
            latlng = poi.location;
            mOverlay.dismissMarker();
            mOverlay.showCurrentmarker(index);
            showAddress(poi.city + poi.name + "(" + poi.address + ")", poi.city);
            return true;
        }

    }


}
